<?php

namespace app\admin\controller\machine;

use app\common\controller\AdminController;
use app\common\lib\Show;
use app\common\lib\Spring;
use app\common\lib\Status;
use app\common\model\MachineCost;
use app\common\model\MachineMachine;
use app\common\model\MachineSeasoning;
use app\common\model\MallSpecsValue;
use app\common\model\SpecsSeasoning;
use think\App;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;

/**
 * @ControllerAnnotation(title="机器管理")
 */
class Machine extends AdminController
{

    use \app\admin\traits\Curd;

    protected array $withAttr = [];
    protected $allowModifyFields = [
        'status',
        'sort',
        'remark',
        'is_delete',
        'is_auth',
        'title',
        'snCode'
    ];

    /**
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new MachineMachine();

    }

    /**
     * @NodeAnotation (title="机器列表")
     * @return array|mixed|\think\response\Json
     * @throws \think\Exception
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames(['title']);
            //dump($this->request->cate_machine);exit();
            if (!empty($this->request->cate_machine)) {
                $where[] = [
                    ['machine_cate', '=', $this->request->cate_machine]
                ];
            }
            $lists = $this->model->getPaginateByNormalListInfo($where, $limit, '*', 'id desc', 'machineCate');
            return Show::json_show(Status::lay_normal, "ok", $lists['data'], $lists['total']);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation (title="同步售货机")
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function asyncMachine()
    {
        //获取同步机器
        try {
            $result = Spring::getInstance()->getMachine(-1, 1, 100);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        dump($result);
        exit();
        if (empty($result['data']['list'])) {
            $this->error("没有机器");
        }
        $lists = [];
        foreach ($result['data']['list'] as $v) {
            $lists[] = [
                "state" => $v['devState'] == 1 ? 1 : 2,
                "machine_id" => $v['snCode'],
                "snCode" => $v['snCode'],
                "devAlias" => $v['devAlias'],
                "devSimCardNum" => $v['devSimCardNum'],
                "devVersion" => $v['devVersion']
            ];
        }
        //查询机器
        $obj = new MachineMachine();
        if (!empty($lists)) {
            //获取机器编码
            $machine_ids = array_column($lists, 'machine_id');
            $machine = $obj->getMachineByMachineIDs($machine_ids, 'id,machine_id');
            $res_machine = array_column($machine, 'id', 'machine_id');
            $insert_data = [];
            foreach ($lists as $k => $v) {
                $insert_data[$k] = $v;
                if (!empty($res_machine[$v['machine_id']])) {
                    $insert_data[$k]['id'] = $res_machine[$v['machine_id']];
                }
            }
            $res = $obj->saveAll($insert_data);
            if ($res) {
                $this->success("同步成功");
            } else {
                $this->error("同步失败");
            }

        } else {
            $this->error("机器不存在");
        }
    }

    /**
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @NodeAnotation(title="授权规格")
     */
    public function authorization($id)
    {
        if ($this->request->isPost()) {
            $machine_id = $this->request->param('machine_id', '', 'trim');
            $items = $this->request->param('items');

            if (empty($machine_id)) {
                $this->error("机器不存在");
            }
            if (empty($items)) {
                $this->error("请输入完整");
            }
            $res = [];
            // todo money 对应的金额 value 对应的类型的id stauts对应的状态
            foreach ($items as $k => $v) {
                if (empty($v['status'])) {
                    $v['status'] = 'no';
                }
                if (empty($v['is_stock'])) {
                    $v['is_stock'] = 'no';
                }
                //根据货道号查询是否存在
                $res_machine = (new MachineCost())->getMachineCostBySpecsIdAndMachineID($k, $machine_id);

                $res[$k] = [
                    "specs_id" => $k ?? 0,
                    "money" => $v['money'] ?? 0,
                    "type" => $v['hot'] ?? 0,
                    "status" => $v['status'] == 'on' ? 1 : 0,
                    "machine_id" => $machine_id,
                    "value" => $v['value'],
                    "stock" => $v['stock'],
                    "is_stock" => $v['is_stock'] == 'on' ? 1 : 0
                ];
                if ($res_machine) {
                    $res[$k]['id'] = $res_machine['id'];
                }
            }
            $result = (new MachineCost())->saveAll($res);
            if ($result) {
                $this->success("保存成功");
            } else {
                $this->error("保存失败");
            }


        }
        $row = $this->model->getBaseById($id);
        if (empty($row)) {
            $this->error("机器不存在");
        }
        //根据机器编号查询 机器商品
        $machine_cost = (new MachineCost())->getBaseByListAll([
            ['machine_id', '=', $row['machine_id']]
        ]);


        $lists = [];
        if (!empty($machine_cost)) {
            $cost_money = array_column($machine_cost, 'money', 'specs_id');
            $cost_value = array_column($machine_cost, 'value', 'specs_id');
            $cost_type = array_column($machine_cost, 'type', 'specs_id');
            $cost_status = array_column($machine_cost, 'status', 'specs_id');
            $cost_stock = array_column($machine_cost, 'stock', 'specs_id');
            $cost_is_stock = array_column($machine_cost, 'is_stock', 'specs_id');
            $specs_ids = array_column($machine_cost, 'specs_id');

            $specs_value = (new MallSpecsValue())->getSpecsValueByList($specs_ids, 'specs');

            if (!empty($specs_value)) {
                foreach ($specs_value as $k => $v) {
                    $lists[$v['specs']['id']]['title'] = $v['specs']['title'];
                    $lists[$v['specs']['id']]['id'] = $v['specs']['id'];
                    $lists[$v['specs']['id']]['list'][] = [
                        "id" => $v['id'],
                        "specs_id" => $v['specs_id'],
                        "title" => $v['title'],
                        "money" => $cost_money[$v["id"]],
                        "value" => $cost_value[$v['id']],
                        "type" => $cost_type[$v['id']],
                        "status" => $cost_status[$v['id']],
                        "stock" => $cost_stock[$v['id']],
                        "is_stock" => $cost_is_stock[$v['id']],
                    ];
                }
            }
        }
        return $this->fetch('', [
            "row" => $row,
            "list" => $lists
        ]);
    }

    /**
     * @NodeAnotation(title="授权口味")
     * @return void
     * @throws \think\Exception
     */
    public function authSeasoning()
    {
        $obj_model = new MachineSeasoning();
        $id = $this->request->param('id',0,'intval');
        if($this->request->isAjax()){
            $res_data = $obj_model->getBaseByListAll([]);
            return Show::json_show(Status::lay_normal,"ok",$res_data);
        }
        try {
            $row = $this->model->getBaseById($id);
        } catch (\Exception $e) {
            $this->error("查询失败");
        }
        if (empty($row)) {
            $this->error("内部异常");
        }
        //查询机器口味是否存在

        $seasoning = $this->getMachineSeasoning($row['machine_id']);
        if (empty($seasoning)) {
            $ret = (new SpecsSeasoning())->getBaseByListAll();
            $insert_data = [];
            foreach ($ret as $v) {
                $insert_data[] = [
                    "title" => $v['title'],
                    "value" => $v['value'],
                    "machine_id" => $row['machine_id'],
                    "create_time" => time(),
                    "update_time" => time()
                ];
            }
            $res = $obj_model->insertAll($insert_data);
            if ($res) {
                $seasoning = $this->getMachineSeasoning($row['machine_id']);
            } else {
                $this->error("添加调料失败");
            }
        }

        $result = [
            "row" => $row,
            "seasoning" => $seasoning
        ];
        return $this->fetch('', [
            "row" => $result
        ]);
    }

    /**
     * @param string $machine_id
     * @return array
     */
    protected function getMachineSeasoning(string $machine_id = ""): array
    {
        $obj_model = new MachineSeasoning();
        try {
            $seasoning = $obj_model->getBaseByListAll([
                ["machine_id", "=", $machine_id],
            ]);
        } catch (\Exception $e) {
            $this->error("查询失败");
        }
        return $seasoning;
    }

    public function dialog()
    {

        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $validate = new \app\common\validate\Machine();
            if (!$validate->check($post)) {
                $this->error($validate->getError());
            }
            //查询机器编号是否存在
            try {
                $res_machine = $this->model->getBaseByListFind([
                    ["machine_id", "=", $post['machine_id']]
                ]);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }

            if ($res_machine) {
                $this->error("机器已经存在！无法添加");
            }
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error("操作失败");
            }

            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $validate = new \app\common\validate\Machine();
            if (!$validate->check($post)) {
                $this->error($validate->getError());
            }
            $id = $this->request->get('id', 0, 'intval');
            try {
                $save = $this->model->updateDataSave($id, $post);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    public function addSeasoning()
    {
        $value = $this->request->param('value', '', 'trim');
        $machine_id = $this->request->param('machine_id', '', 'trim');
        if (empty($value)) {
            $this->error("请输入后回车");
        }
        if (empty($machine_id)) {
            $this->error("机器编码不存在");
        }
        //判断口味是否存在
        $obj_model = new MachineSeasoning();
        try {
            $res = $obj_model->getBaseByListFind([
                "machine_id" => $machine_id,
                "title" => $value
            ]);
        } catch (\Exception $e) {
            $this->error("查询失败");
        }
        if ($res) {
            $this->error("该口味已经存在");
        } else {
            $insert_data = [
                "machine_id" => $machine_id,
                "title" => $value
            ];
            $res = $obj_model->save($insert_data);

            if ($res) {
                return Show::json_show(Status::status_normal,"添加成功",[
                    "id"=>$obj_model->id
                ]);
            } else {
                $this->error("添加失败");
            }
        }
    }
}